//
//  XYJChangeMoneyViewController.m
//  徙游记-01
//
//  Created by hcios on 2017/7/17.
//  Copyright © 2017年 鹿林. All rights reserved.
//

#import "XYJChangeMoneyViewController.h"
#import "XYJChangeTableViewCell.h"

@interface XYJChangeMoneyViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    UITableView *_tableView;
    NSMutableArray *_rateArr;
    NSMutableArray *_resultArr;
}

@property (nonatomic,strong) UITextField *moneyField;
@property (nonatomic,strong) UILabel *changeLabel;

@end

@implementation XYJChangeMoneyViewController

-(instancetype)init{
    if (self = [super init]) {
        _rateArr = [[NSMutableArray alloc] init];
        NSArray *textLabel = @[@"0.00",@"0.00",@"0.00"];
        _resultArr = [NSMutableArray arrayWithArray:textLabel];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"汇率转换";
    [self setupRightBtn];
    [self moneyField];
    [self changeLabel];
    [self initTable];
    
}

-(void)initTable{
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        NSString *cellID = @"cellID";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        cell.textLabel.text = _cityMoneyCode;
        [cell addSubview:_moneyField];
        return cell;
    }else{
        NSString *cellID = [NSString stringWithFormat:@"cellID%ld%ld",(long)[indexPath section],(long)[indexPath row]];
        XYJChangeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[XYJChangeTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        }
        NSArray *titleArr = @[@"CNY",@"USD",@"EUR"];
        [cell layoutCellWithTitle:titleArr[indexPath.row - 1] andMoney:_resultArr[indexPath.row - 1]];
        return cell;
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}



#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


-(void)setupRightBtn{
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setFrame:CGRectMake(0, 0, 60, 40)];
    [rightBtn setTitle:@"转换" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn.titleLabel setFont:[UIFont fontWithName:FONT_NAME_LTH size:14]];
    [rightBtn addTarget:self action:@selector(clickChange) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBarBtn;
}


-(void)clickChange{
    NSLog(@"点击转换");
    [_rateArr removeAllObjects];
    NSString *urlString = @"http://chanyouji.com/api/currency_exchanges.json";
    [[SeverceHttpRequest sharedManager] GET:urlString parameters:nil success:^(id reponseObject) {
        
        for (NSDictionary *dict in reponseObject) {
            
            if ([dict[@"currency_from"] isEqualToString:_cityMoneyCode]) {
                //通过判断取出对应数据
                if ([dict[@"currency_to"] isEqualToString:@"CNY"]) {
                    [_rateArr addObject:dict[@"exchange_rate"]];
                    }
                    
                if ([dict[@"currency_to"] isEqualToString:@"USD"]) {
                        [_rateArr addObject:dict[@"exchange_rate"]];
                    }
                if ([dict[@"currency_to"] isEqualToString:@"EUR"]) {
                            [_rateArr addObject:dict[@"exchange_rate"]];
                    }
            }
        }
        //添加判断(防止数组为空，造成越界)
        if (_rateArr.count == 2) {
            if ([_cityMoneyCode isEqualToString:@"CNY"]) {
                [_rateArr insertObject:@"1.0" atIndex:0];
            }
            if ([_cityMoneyCode isEqualToString:@"USD"]) {
                [_rateArr insertObject:@"1.0" atIndex:1];
            }
            if ([_cityMoneyCode isEqualToString:@"EUR"]) {
                [_rateArr insertObject:@"1.0" atIndex:2];
            }
        }
        [self changeMoney:_moneyField.text andrateArr:_rateArr];
        [_tableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"网络请求失败");
    }];
}

//换算算法
-(void)changeMoney:(NSString *)textFieldText andrateArr:(NSMutableArray *)rateArr{
    //清空数组
    [_resultArr removeAllObjects];
    
    //添加判断是美国的汇率有顺序
    if ([_cityMoneyCode isEqualToString:@"USD"]) {
        [rateArr exchangeObjectAtIndex:0 withObjectAtIndex:1];
        [rateArr exchangeObjectAtIndex:1 withObjectAtIndex:2];
    }
    //通过汇率计算转化结果
    for (NSString *rate in rateArr) {
        CGFloat floatRate = [rate floatValue];
        CGFloat moneyText = [textFieldText floatValue];
        NSString *result = [NSString stringWithFormat:@"%.2f",(moneyText * floatRate)];
        [_resultArr addObject:result];
    }
}


-(UITextField *)moneyField{
    if (_moneyField == nil) {
        _moneyField = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2, 20, SCREEN_WIDTH / 2 - 10, 40)];
        _moneyField.textAlignment = NSTextAlignmentRight;
        _moneyField.placeholder = @"0.00";
    }
    return _moneyField;
}






@end
